package cn.jxau.interceptor;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import cn.jxau.bean.po.User;
import cn.jxau.bean.vo.JsonResult;
import cn.jxau.common.util.JacksonUtils;

/**
 * 用作用户级权限控制
 * @author licho
 *
 */
public class PrivilegeVlidateInterceptor implements HandlerInterceptor {
	private Logger log=Logger.getLogger(PrivilegeVlidateInterceptor.class);
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		boolean flag=true;
		HttpSession session=request.getSession();
		String contextPath=request.getContextPath();
		User user=(User)session.getAttribute("user");
		if(user==null){
			//说明 没有登录，
			if(log.isDebugEnabled())
				log.debug("我拦截了请求:"+request.getServletPath());
			flag=false;
			boolean isResp=request.getParameter("_login")==null ? false :true;
			if(isResp){
				printJsonMessage(response, getAccessJson());
			}else{
				response.sendRedirect(contextPath+"/jsp/login");
			}
		}
		return flag;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub

	}
	/**
	 * 对于某些ajax请求拦截的页面的要求进行回应的页面，通过403错误告知其请求权限不够
	 * @return
	 */
	private String getAccessJson(){
		JsonResult result=new JsonResult();
		result.setMsg("权限不足");
		result.setStatus("403");//权限不足
		return JacksonUtils.converToJson(result);
	}
	
	private void printJsonMessage(HttpServletResponse resp,String msg){
		resp.setCharacterEncoding("UTF-8");
		resp.setContentType("application/json;charset=utf-8");
		try {
			PrintWriter writer=resp.getWriter();
			writer.write(msg);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
